import React, { useEffect, useState } from 'react';
import { Table, Button, Space, Input, message, Modal } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { simpleListCommentPage, deleteComment } from '@/api/commentController';
import type { CommentData } from '@/types/comment';
import ReplyListModal from './ReplyListModal';

export default function CommentManagement() {
  const [comments, setComments] = useState<CommentData[]>([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchContent, setSearchContent] = useState('');
  const [loading, setLoading] = useState(false);
  const [selectedReplies, setSelectedReplies] = useState<CommentReply[]>([]);
  const [replyModalVisible, setReplyModalVisible] = useState(false);

  const fetchComments = async (page: number, content: string = '') => {
    setLoading(true);
    try {
      const response = await simpleListCommentPage({
        current: page,
        pageSize,
        content,
        targetType: 0, // 默认显示图书评论
      });
      if (response.data) {
        setComments(response.data.records);
        setTotal(parseInt(response.data.total));
      }
    } catch (error) {
      message.error('获取评论列表失败');
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchComments(current, searchContent);
  }, [current, pageSize]);

  const handleDelete = async (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条评论吗？',
      onOk: async () => {
        try {
          await deleteComment({ id });
          message.success('删除成功');
          fetchComments(current, searchContent);
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const columns: ColumnsType<CommentData> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '目标ID',
      dataIndex: 'targetid',
      key: 'targetid',
      width: 80,
    },
    {
      title: '评论类型',
      dataIndex: 'targettype',
      key: 'targettype',
      width: 100,
      render: (type) => type === 0 ? '图书评论' : '帖子评论',
    },
    {
      title: '评论内容',
      dataIndex: 'content',
      key: 'content',
      width: 200,
    },
    {
      title: '评论时间',
      dataIndex: 'commenttime',
      key: 'commenttime',
      width: 160,
    },
    {
      title: '评论人信息',
      dataIndex: 'userInfo',
      key: 'userInfo',
      width: 300,
      render: (userInfo) => (
        <div>
          <p>用户名：{userInfo.nickName}</p>
          <p>邮箱：{userInfo.email}</p>
          <p>性别：{userInfo.gender === 0 ? '男' : '女'}</p>
          <p>城市：{userInfo.address}</p>
        </div>
      ),
    },
    {
      title: '回复数量',
      dataIndex: 'commentReplies',
      key: 'replyCount',
      width: 100,
      render: (replies) => replies.length,
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="primary"
            onClick={() => {
              setSelectedReplies(record.commentReplies);
              setReplyModalVisible(true);
            }}
          >
            查看回复({record.commentReplies.length})
          </Button>
          <Button type="link" danger onClick={() => handleDelete(record.id)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Input.Search
          placeholder="搜索评论内容"
          style={{ width: 300 }}
          onSearch={(value) => {
            setSearchContent(value);
            setCurrent(1);
            fetchComments(1, value);
          }}
        />
      </div>
      <Table 
        columns={columns} 
        dataSource={comments}
        rowKey="id"
        loading={loading}
        pagination={{
          current,
          pageSize,
          total,
          onChange: (page) => {
            setCurrent(page);
          },
          onShowSizeChange: (_, size) => {
            setPageSize(size);
            setCurrent(1);
          },
        }}
      />
      <ReplyListModal
        visible={replyModalVisible}
        onClose={() => setReplyModalVisible(false)}
        replies={selectedReplies}
        onDelete={() => {
          fetchComments(current, searchContent);
          setReplyModalVisible(false);
        }}
      />
    </div>
  );
} 